<template>
  <a-modal
    v-model:visible="visible"
    title="选择业务字段"
    width="800px"
    :mask-closable="false"
    :keyboard="false"
    @ok="handleOk"
  >
    <a-spin :spinning="loading">
      <template v-if="fieldlist.length">
        <a-card>
          <a-checkbox-group v-model:value="fieldChecked" :style="{ width: '100%' }">
            <a-tabs v-model:activeKey="activeKey" :tab-bar-style="{ height: maxHeight + 'px' }" tab-position="left">
              <a-tab-pane v-for="item in fieldlist" :key="item.groupId">
                <template #tab>
                  <customShowTooltips :max-width="200" :content="item.groupName"></customShowTooltips>
                </template>
                <a-row>
                  <a-col v-for="field in item.fieldList" :key="field.fieldId" :span="6">
                    <a-checkbox :label="field.fieldName" :value="field.fieldId">
                      <span>{{ field.fieldName }}</span>
                    </a-checkbox>
                  </a-col>
                </a-row>
              </a-tab-pane>
            </a-tabs>
          </a-checkbox-group>
        </a-card>
      </template>
      <IcpEmpty v-else></IcpEmpty>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { businessFieldlist, fieldDetailList } from '@@/api/form/businessField'
import { v4 } from 'uuid'
const visible = ref(false)
const activeKey = ref()
const fieldlist = ref()
const fieldChecked = ref<any[]>()
const loading = ref<boolean>(false)
const emits = defineEmits(['submit'])
const maxHeight = window.innerHeight - 350

const handleOk = () => {
  visible.value = false
  fieldDetailList({ fieldIds: fieldChecked.value?.join(',') }).then((res: any) => {
    res.forEach((item: any) => {
      const id = item.fieldId
      item.fieldId = v4().replaceAll('-', '')
      // 业务字段提交的时候需要增加一个sourceFieldId属性
      item.sourceFieldId = id
    })
    emits('submit', res)
  })
}
const show = () => {
  visible.value = true
  fieldChecked.value = []
  fieldlist.value = []
  getFieldList()
}

const getFieldList = () => {
  loading.value = true
  businessFieldlist().then((res) => {
    fieldlist.value = res
    activeKey.value = res[0].groupId
    loading.value = false
  })
}

defineExpose({
  show
})
</script>
